package j20251028;

import java.util.concurrent.atomic.AtomicStampedReference;

public class Demo2 {
    private AtomicStampedReference<String> ref =
            new AtomicStampedReference<>("initial", 0);

    // 获取引用和版本号
    public void getValueAndStamp() {
        int[] stampHolder = new int[1];
        String value = ref.get(stampHolder);
        int stamp = stampHolder[0];

        System.out.println("值: " + value + ", 版本: " + stamp);
    }

    // 设置新值和版本号
    public void setValue(String newValue, int newStamp) {
        ref.set(newValue, newStamp);
    }

    // 尝试原子更新
    public boolean tryUpdate(String expectedValue, String newValue,
                             int expectedStamp, int newStamp) {
        return ref.compareAndSet(expectedValue, newValue,
                expectedStamp, newStamp);
    }
}
